package com.weasel.weixin.commons.session.mgt.scheduler;

import com.weasel.helper.TaskScheduledExecutor;
import com.weasel.weixin.commons.session.mgt.AbstractWeixinValidatingSessionManager;
import com.weasel.weixin.commons.session.mgt.WeixinValidatingSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by Dylan on 2015/12/8.
 */
public class ExecutorServiceSessionValidationScheduler implements SessionValidationScheduler{

    private final static Logger logger = LoggerFactory.getLogger(ExecutorServiceSessionValidationScheduler.class);

    private boolean isEnabled;
    private long interval;
    private WeixinValidatingSessionManager sessionManager;
    private TaskScheduledExecutor scheduledExecutor = TaskScheduledExecutor.scheduled();

    public ExecutorServiceSessionValidationScheduler(WeixinValidatingSessionManager sessionManager) {
        this.sessionManager = sessionManager;
        this.isEnabled = false;
        interval = AbstractWeixinValidatingSessionManager.DEFAULT_SESSION_VALIDATION_INTERVAL;
    }

    public void setIsEnabled(boolean isEnabled) {
        this.isEnabled = isEnabled;
    }

    public WeixinValidatingSessionManager getSessionManager() {
        return sessionManager;
    }

    public void setSessionManager(WeixinValidatingSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public long getInterval() {
        return interval;
    }

    public void setInterval(long interval) {
        this.interval = interval;
    }

    @Override
    public boolean isEnabled() {
        return isEnabled;
    }

    @Override
    public void enableSessionValidation() {

        if(this.interval > 0l){
            logger.info("enable session validation,interval time is {} millisecond", this.interval);
            scheduledExecutor.submitTask(new Runnable() {
                @Override
                public void run() {
                    if (logger.isInfoEnabled()) {
                        logger.info("validate session task start execute");
                    }
                    try {
                        getSessionManager().validateSessions();
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }, this.interval, TimeUnit.MILLISECONDS);
            this.isEnabled = true;
        }
    }

    @Override
    public void disableSessionValidation() {
        logger.info("disable session validation");
        scheduledExecutor.shutdown();
        this.isEnabled = false;
    }
}
